package com.xhwl.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhwl.common.dto.cent.sdata.GroupDTO;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.GroupAccount;
import com.xhwl.common.query.cent.sdata.GroupQuery;
import com.xhwl.data.dao.IGroupAccountDao;
import com.xhwl.data.dao.IGroupDao;
import com.xhwl.data.service.IGroupAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author JCccc
 * @Description
 * @Date 2021/6/15 17:03
 */
@Service
public class GroupAccountServiceImpl extends ServiceImpl<IGroupAccountDao, GroupAccount> implements IGroupAccountService {
    @Autowired
    IGroupAccountDao groupAccountDao;
    @Autowired
    IGroupDao groupDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson createGroupAccount(Integer groupId, List<Integer> accountIds) {

        try {
            //先删除后新增
            UpdateWrapper<GroupAccount> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("group_id", groupId);
            groupAccountDao.delete(updateWrapper);
            List<GroupAccount> groupAccountList = new ArrayList<>(accountIds.size());
            if (CollectionUtils.isEmpty(accountIds)) {
                return ResultJson.fail("缺少账号参数");
            }
            for (int accountId : accountIds) {
                GroupAccount groupAccount = new GroupAccount();
                groupAccount.setAccountId(accountId);
                groupAccount.setGroupId(groupId);
                groupAccountList.add(groupAccount);
            }
            //批量新增 账号与用户组权限
            saveBatch(groupAccountList);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultJson.fail("操作失败");
        }
        return ResultJson.success("操作成功");

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson addGroupAccount(Integer groupId, List<Integer> accountIds) {

        try {
            QueryWrapper<GroupAccount> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("group_id", groupId);
            queryWrapper.in("account_id", accountIds);
            List<GroupAccount> groupAccounts = groupAccountDao.selectList(queryWrapper);
            List<Integer> accountIdDbList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(groupAccounts)) {
                accountIdDbList = groupAccounts.stream().map(e -> e.getAccountId()).collect(Collectors.toList());
            }
            List<Integer> needAddAccountIds = new ArrayList<>();
            if (CollectionUtils.isEmpty(accountIdDbList)) {
                needAddAccountIds.addAll(accountIds);
            } else {
                //移除数据库内已经存在的关联关系的账号id，避免批量新增时重复导致报错
                for (Integer accountId : accountIds) {
                    if (!accountIdDbList.contains(accountId)) {
                        needAddAccountIds.add(accountId);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(needAddAccountIds)) {
                List<GroupAccount> groupAccountList = new ArrayList<>(needAddAccountIds.size());
                for (int accountId : needAddAccountIds) {
                    GroupAccount groupAccount = new GroupAccount();
                    groupAccount.setAccountId(accountId);
                    groupAccount.setGroupId(groupId);
                    groupAccountList.add(groupAccount);
                }
                //批量新增 账号与用户组权限
                saveBatch(groupAccountList);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultJson.fail("操作失败");
        }
        return ResultJson.success("操作成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson deleteGroupAccount(List<Integer> groupIds, List<Integer> accountIds) {
        try {
            UpdateWrapper<GroupAccount> updateWrapper = new UpdateWrapper<>();
            if (!CollectionUtils.isEmpty(groupIds)) {
                updateWrapper.in("group_id", groupIds);
            }
            if (!CollectionUtils.isEmpty(accountIds)) {
                updateWrapper.in("account_id", accountIds);
            }
            groupAccountDao.delete(updateWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultJson.fail("删除用户组账号关联表失败");
        }
        return ResultJson.success("操作成功");
    }

    @Override
    public List<GroupAccount> getList(List<Integer> groupIds, List<Integer> accountIds) {
        QueryWrapper<GroupAccount> queryWrapper = new QueryWrapper<>();
        if (!CollectionUtils.isEmpty(accountIds)) {
            queryWrapper.in("account_id", accountIds);
        }
        if (!CollectionUtils.isEmpty(groupIds)) {
            queryWrapper.in("group_id", groupIds);
        }
        List<GroupAccount> groupAccounts = groupAccountDao.selectList(queryWrapper);
        return groupAccounts;
    }

    @Override
    public Page<GroupDTO> getGroupPageList(Page page, GroupQuery groupQuery) {
        //处理需要查询id集合
        Set<Integer> needQueryGroupIds = new HashSet<>();
        if (!CollectionUtils.isEmpty(groupQuery.getAccountIds())) {
            List<GroupAccount> groupAccounts = this.getList(null, groupQuery.getAccountIds());
            for (GroupAccount groupAccount : groupAccounts) {
                needQueryGroupIds.add(groupAccount.getGroupId());
            }
        }
        if (!CollectionUtils.isEmpty(groupQuery.getIdList())) {
            needQueryGroupIds.addAll(groupQuery.getIdList());
        }
        if (CollectionUtils.isEmpty(needQueryGroupIds)) {
            groupQuery.setIdList(new ArrayList<>(needQueryGroupIds));
        }
        Page<GroupDTO> groupPageList = groupDao.getPageList(page, groupQuery);
        return groupPageList;
    }

}
